<template>
  <div id="documentPlay" class="scrolling" ref="player">
    <div class="container" ref="container">
      <!-- 最短学习时间提示 -->
      <div id="time-tip-top">
        <div class="time-tip-top-main">
          <i class="iconfont icon-tishi"></i>
          <span
            >最短学习时长为<span>{{ timeFormat }}</span></span
          >,
          <span v-if="learnProgress == '100'">您已学习完成</span>
          <span v-else>学习中：{{ timeShow }}</span>
        </div>
        <div class="bg-color"></div>
      </div>
      <div class="document-content" ref="documentContent">
        <div id="document_container"></div>
      </div>
    </div>
  </div>
</template>

<style src="./index.less" lang="less" scoped></style>

<script>
import { updateCourseLearning, getCourseLessonsDetail, getDocumentToken } from '@/api/course'

import watermark from '@/assets/js/watermark'

export default {
  name: 'documentPlay',
  props: ['courseId', 'coursewareId', 'isDrag', 'from'],
  data() {
    return {
      stageId: this.$route.query.stageId, // 阶段ID
      trainId: this.$route.query.trainId, // 培训ID
      instance: null,
      tokenInfo: {},
      screenWidth: null,
      documentId: '',
      learnTime: '', // 学员已学习时间
      documentLength: 0, // 文档需要学习时间
      learnProgress: '0', // 学习进度
      countInter: null, // 计时器
      timeFormat: '', // 最少阅读时间
      timeShow: '', // 倒计时
      nextCourseware: {}, // 下一节
      lessonInfo: {},
      waterTxt: '', // 水印字段
      TimingUpdateProgress: null, // 30s定时器
      transCodeUri: '', // 阿里云地址
      sourceId: '',
      setTimer: null,
      lessonData: {}
    }
  },
  watch: {
    $route() {
      this.randerPlayer()
    },
    coursewareId: {
      handler(val) {
        clearTimeout(this.setTimer)
        clearInterval(this.countInter)
        clearInterval(this.TimingUpdateProgress)
        if (this.instance) {
          this.instance.destroy()
        }
        this.setTimer = setTimeout(() => {
          this.$router.go(0)
        }, 240)
      },
      deep: true,
      immediate: false
    }
  },
  mounted() {
    if (this.from == 'train') {
      this.sourceId = this.$route.query.trainId
    } else {
      this.sourceId = this.courseId
    }
    this.getLessonDetail()
    // 设置ppt预览容器高度，高度小于宽度，避免横屏
    this.screenWidth = window.screen.width
    document.oncontextmenu = () => {
      return false
    }
    clearInterval(this.countInter)
    clearInterval(this.TimingUpdateProgress)

    document.addEventListener('visibilitychange', this.handleVisibilitychange)
  },
  methods: {
    /**
     * 获取课程信息详情
     */
    getLessonDetail() {
      getCourseLessonsDetail(this.coursewareId, {
        from: this.from,
        sourceId: this.sourceId,
        courseId: this.courseId,
        stageId: this.stageId ? this.stageId : this.courseId
      })
        .then(res => {
          this.lessonData = res.data
          // 下节课件
          this.nextCourseware = this.lessonData.nextCourseware ? this.lessonData.nextCourseware : {}
          if (this.nextCourseware.uuid) {
            this.lessonInfo = {
              title: this.nextCourseware.title,
              courseId: this.nextCourseware.courseId,
              uuid: this.nextCourseware.uuid,
              coursewareType: this.nextCourseware.type
            }
          } else {
            this.lessonInfo = {
              uuid: ''
            }
          }

          this.transCodeUri = this.lessonData.transCodeUri
          this.learnProgress = this.lessonData.progress
          // 文档观看时间
          this.learnTime = this.lessonData.progressBar
          // 文档需要学习时间
          this.documentLength = this.lessonData.length

          this.tokenInfo = {
            WebofficeURL: this.lessonData.transCodeUri,
            AccessToken: this.lessonData.accessToken,
            RefreshToken: this.lessonData.refreshToken
          }
          this.previewDocument(this.tokenInfo)

          this.waterTxt = window.localStorage.getItem('companyName')
          if (this.waterTxt) {
            watermark({
              watermark_id: 'documentPlay',
              watermark_txt: this.waterTxt,
              watermark_fontsize: '14px',
              watermark_x: 0,
              watermark_x_space: 30,
              watermark_width: 140,
              watermark_cols: 5
            })
          }

          this.randerPlayer()
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 预览
    async previewDocument(tokenInfo) {
      let mount = document.querySelector('#document_container')
      this.instance = aliyun.config({
        mount,
        url: tokenInfo.PreviewURL || tokenInfo.EditURL || tokenInfo.WebofficeURL,
        mode: 'simple',
        refreshToken: this.refreshToken()
      })
      this.instance.setToken({ token: tokenInfo.AccessToken, timeout: 25 * 60 * 1000 })

      this.instance.on('fileOpen', function (data) {
        console.log(data)
      })

      this.instance.on('error', err => {
        console.log('发生错误：', err)
      })

      //等待instance ready之后再显示课程倒计时
      await this.instance.ready()
      console.log('加载完成')
      await this.setLearnTime()
    },
    // 重新获取token
    refreshToken() {
      let _self = this
      let lastTokenInfo = this.tokenInfo
      return new Promise(function (resolve) {
        //业务处理逻辑，调用服务端封装的refreshToken接口。
        getDocumentToken({
          refreshToken: lastTokenInfo.RefreshToken,
          accessToken: lastTokenInfo.AccessToken
        })
          .then(res => {
            let data = res.data
            _self.tokenInfo = {
              WebofficeURL: lastTokenInfo.WebofficeURL,
              AccessToken: data.accessToken,
              RefreshToken: data.refreshToken
            }
            lastTokenInfo = _self.tokenInfo
            resolve({
              token: _self.tokenInfo.AccessToken, //必须设置。
              timeout: 25 * 60 * 1000 // 必须设置，Token超时时间，单位为ms，示例设置超时时间为25分钟。可配合refreshToken配置函数使用，在超时前5分钟调用refreshToken重新刷新Token。
            })
          })
          .catch(err => {
            console.log(err)
            getCourseLessonsDetail(_self.$route.query.coursewareId, {
              from: _self.from,
              sourceId: _self.sourceId,
              courseId: _self.courseId,
              stageId: _self.stageId ? _self.stageId : _self.courseId
            }).then(res => {
              console.log(res)
              let data = res.data
              _self.tokenInfo = {
                WebofficeURL: data.transCodeUri,
                AccessToken: data.accessToken,
                RefreshToken: data.refreshToken
              }
              lastTokenInfo = _self.tokenInfo
              resolve({
                token: _self.tokenInfo.AccessToken, //必须设置。
                timeout: 25 * 60 * 1000 // 必须设置，Token超时时间，单位为ms，示例设置超时时间为25分钟。可配合refreshToken配置函数使用，在超时前5分钟调用refreshToken重新刷新Token。
              })
            })
          })
      })
    },

    async setLearnTime() {
      // 设置最短学习时间提示
      this.timeFormat = this.$_courseCountDown(this.documentLength)
      // 开始计时(课程未完成时才进行计时)
      if (this.learnProgress == '100') {
        this.timeShow = this.$_courseCountDown(this.documentLength, 'count')
      } else {
        if (parseInt(this.learnTime) < parseInt(this.documentLength)) {
          this.countInter = setInterval(() => {
            this.learnTime++
            // 判断是否达完成学习
            if (parseInt(this.learnTime) >= parseInt(this.documentLength)) {
              clearInterval(this.countInter)
              clearInterval(this.TimingUpdateProgress)
              this.updateRecordTime()
            }
            this.timeShow = this.$_courseCountDown(this.learnTime, 'count')
          }, 1000)
          // 定时同步进度（30s一次）
          this.TimingUpdateProgress = setInterval(() => {
            this.updateRecordTime()
          }, 30000)
        } else {
          this.timeShow = this.$_courseCountDown(this.documentLength, 'count')
          this.updateRecordTime()
        }
      }
    },

    // 记录当前学习进度
    updateRecordTime() {
      if (this.lessonData.uuid) {
        updateCourseLearning({
          coursewareId: this.lessonData.uuid,
          progressBar: Number(this.learnTime).toFixed(2),
          from: this.from,
          sourceId: this.sourceId,
          courseId: this.courseId,
          stageId: this.stageId ? this.stageId : this.courseId
        })
          .then(res => {
            if (res.data.progress == '100' && res.data.open) {
              this.$emit('nextLessonPlay', this.lessonInfo)
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    },

    /**
     * 监听页面显示隐藏时的操作
     */
    handleVisibilitychange() {
      if (document.hidden) {
        clearInterval(this.countInter)
        clearInterval(this.TimingUpdateProgress)
        this.updateRecordTime()
      } else {
        this.setLearnTime()
      }
    },

    // 设置播放器的高度
    randerPlayer() {
      window.setTimeout(() => {
        let _height = window.getComputedStyle(this.$refs.documentContent, null)['height']
        let _children = this.$refs.documentContent.childNodes
        for (let i = 0; i < _children.length; i++) {
          _children[0].style.height = _height
        }
      }, 300)
    }
  },

  beforeDestroy() {
    if (this.instance) {
      this.instance.destroy()
    }

    document.removeEventListener('visibilitychange', this.handleVisibilitychange)
    this.updateRecordTime()

    clearInterval(this.countInter)
    clearInterval(this.TimingUpdateProgress)
  }
}
</script>
